/*初始化音视频*/
define(['js/lib/async.min', 'js/plugins/chat/chat.common', 'js/plugins/chat/i18n/chat.' + $E.lang, 'js/plugins/chat/jquery.rateyo.min'], function (async, $COMM,i18n) {
    var chatServerAddr,
        Tools = $COMM.Tools,
        tools,
        restApi,
        accessToken,
        roomId,
        sessionId,
        localVideoId = '',
        localAudioId = '',
        isOpenVideoShow,
        isOpenAudioShow,
        audioIconAreaElement,
        videoIconAreaElement,
        remoteVideoIconAreaElement,
        remoteAudioIconAreaElement,
        localVideo,
        remoteAudio,
        remoteVideo,
        sendMessage
    //调用服务接口
    var callService = function (params, retry) {
        if (params && params.url) {
            params.url = tools.chatServerAddr + "/" + params.url;
        }
        return tools.callService(params, (retry ? 0 : undefined));
    };
    var RestApi = function (serverURI) {
        function fetchGet(url, params) {
            var deferred = $.Deferred();
            var fullUrl = document.location.protocol + '//' + serverURI + '/sdkapi/v2' + url;
            // 发送Ajax请求
            $.ajax({
                url: fullUrl,
                method: 'GET',
                data: params.params,
                timeout: 5000,
                success: function (response) {
                    if (response.ret === 0) {
                        deferred.resolve(response);
                    } else {
                        deferred.reject(response);
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    var data = {
                        ret: xhr.status,
                        msg: errorThrown
                    };
                    deferred.reject(data);
                }
            });

            return deferred.promise();
        }

        function fetchPost(url, params) {
            var deferred = $.Deferred();
            // 发送Ajax请求
            $.ajax({
                url: url,
                method: 'POST',
                data: params.params,
                processData: false,  // 不处理数据
                contentType: 'multipart/form-data',  // 不设置Content-Type头部信息
                timeout: 5000,
                success: function (response) {
                    if (response.ret === 0) {
                        deferred.resolve(response.data);
                    } else {
                        var error = {
                            code: response.ret,
                            message: response.msg
                        };
                        deferred.reject(error);
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status === 200) {
                        var response = xhr.responseJSON || {};
                        var error = {
                            code: response.ret || 0,
                            message: response.msg || 'Unknown error'
                        };
                        deferred.reject(error);
                    } else {
                        var error = {
                            code: xhr.status,
                            message: errorThrown
                        };
                        deferred.reject(error);
                    }
                }
            });

            return deferred.promise();
        }

        /**
         * 获取访问令牌
         * @param {String} access_key
         * @param {String} secret_key
         */
        this.getAccessToken = function (access_key, secret_key) {
            return fetchGet('/app/get_token', {params: {"access_key": access_key, "secret_key": secret_key}});
        }

        /**
         * 创建房间
         * @param {String} token-访问令牌
         * @param {String} topic-会议主题
         * @param {Boolean} enable_auto_cloud_recording-是否开启云端自动录制，默认false
         * @param {String} user_id-房间创建者用户ID
         * @param {String} room_id-指定房间ID，如果不传服务器生成随机号
         * @param {Boolean} enable_auto_avc-是否启用自动视频AVC模式（视频合屏），默认false
         */
        this.createRoom = function (token, topic, user_id, room_id, enable_auto_cloud_recording, enable_auto_avc) {
            var paramsObj = {
                "token": token,
                "topic": topic,
                "user_id": user_id,
            }

            if (room_id) {
                paramsObj.room_id = room_id;
            }

            if (enable_auto_cloud_recording) {
                paramsObj.enable_auto_cloud_recording = enable_auto_cloud_recording;
            }

            if (enable_auto_avc) {
                paramsObj.enable_auto_avc = enable_auto_avc;
            }

            return fetchGet('/room/create', {params: paramsObj});
        }
        this.delRoom = function (token, room_id) {
            const paramsObj = {
                "token": token,
                "room_id": room_id
            };
            return fetchGet('/room/del', {params: paramsObj});
        }

        /**
         * 查询房间录制
         * @param {String} token-访问令牌
         * @param {String} room_id-房间ID
         * @param {String} record_start_time-录制起始时间
         * @param {String} record_end_time-录制结束时间
         */
        this.queryRoomRecording = function (token, room_id, record_start_time, record_end_time) {
            return fetchGet('/room/get_record', {
                params: {
                    "token": token,
                    "room_id": room_id,
                    "record_start_time": record_start_time,
                    "record_end_time": record_end_time,
                }
            });
        }


        /**
         * 开始AVC合屏模式
         * @param {String} token-访问令牌
         * @param {String} room_id-房间ID
         */
        this.startAvcModel = function (token, room_id) {
            return fetchGet('/room/avc/start', {params: {"token": token, "room_id": room_id}});
        }

        /**
         * 停止AVC合屏模式
         * @param {String} token-访问令牌
         * @param {String} room_id-房间ID
         */
        this.stopAvcModel = function (token, room_id) {
            return fetchGet('/room/avc/stop', {params: {"token": token, "room_id": room_id}});
        }

        /**
         * 关闭房间的接口，用于将所有用户从房间踢出，包括设备和录制
         * @param {String} token-访问令牌
         * @param {String} room_id-房间ID
         */
        this.closeRoom = function (token, room_id) {
            return fetchGet('/room/close', {params: {"token": token, "room_id": room_id}});
        }
        this.mixRecordStart = function (token, room_id) {
            return fetchGet('/room/mix_record/start', {
                params: {
                    "token": token,
                    "room_id": room_id,
                    "enable_realtime_transcode": true
                }
            });
        }
        this.mixRecordEnd = function (token, room_id) {
            return fetchGet('/room/mix_record/stop', {params: {"token": token, "room_id": room_id}});
        }

        /**
         * 上传图片
         * @param {String} token-访问令牌
         * @param {String} room_id-房间ID
         * @param {String} user_id-用户ID
         */
        this.uploadImg = function (token, room_id, user_id) {
            return fetchPost('/file/upload_file?token=' + token + '&room_id=' + room_id + '&user_id=' + user_id);
        }
    }

    var Meet = {
        init: function (sendMsg,chatServerUrl, initParam, meetSessionId, userName, container, acceptRoomId) {
            var Container = container
            var serverURL = initParam.sanTiServerUrl;
            var accessKey = initParam.sanTiAccessKey;
            var secretKey = initParam.sanTiSecretKey;
            var isVideoFacility = false
            var isAudioFacility = false
            var userId = $E.staff.id;
            var AVDEngine = ModuleBase.use(ModulesEnum.avdEngine);
            var avdEngine = new AVDEngine();
            sendMessage = sendMsg
            chatServerAddr = chatServerUrl
            tools = new Tools(chatServerAddr, 5);
            sessionId = meetSessionId
            avdEngine.initDevice().then(initDeviceSuccess);
            avdEngine.checkDevice().then(checkResult).inspect(checkError)
            // 设置视频编码格式默认VP8
            // avdEngine.setVideoCoding(VideoCodingType.VP8);
            restApi = new RestApi(serverURL);
            audioIconAreaElement = document.querySelector('.audioIconArea')
            videoIconAreaElement = document.querySelector('.videoIconArea')
            remoteVideoIconAreaElement = document.querySelector('.remoteVideoIconArea')
            remoteAudioIconAreaElement = document.querySelector('.remoteAudioIconArea')
            localVideo = document.querySelector("#selfvideo")
            remoteAudio = document.querySelector("#remoteAudio")
            remoteVideo = document.querySelector("#othervideo")
            isOpenVideoShow = true
            isOpenAudioShow = true
            $('#othervideo', Container).hide();
            function checkResult(result) {
                isVideoFacility = result.video;
                isAudioFacility = result.audio;
            }

            function initDeviceSuccess(state) {
                if (state && state === 1) {
                    $F.log('+++initDevicSuccess')
                    getAccessToken()
                }
            }

            function checkError(error) {
                $F.err("getDeviceError!errorCode:" + error.code + "; errorMessage:" + error.message);
            }

            function getAccessToken() {
                restApi.getAccessToken(accessKey, secretKey).then((res) => {
                    accessToken = res.token;
                    acceptRoomId ? joinRoom() : createRoom()
                }).catch((error) => {
                    $F.alert(i18n.error.uploadFailed + ': ' + error);
                })
            }

            //创建房间
            function createRoom() {
                var topic = 'videoMeeting';
                restApi.createRoom(accessToken, topic, userId, '').then((res) => {
                    roomId = res.room_id
                    joinRoom()
                }).catch((error) => {
                    $F.alert(i18n.error.uploadFailed + 'createRoomError: ' + error);
                })
            }

            //  加入会议
            function joinRoom() {
                if (room) {
                    return
                }
                if (!isVideoFacility) {
                    $F.alert(i18n.error.cameraDeviceState);
                } else if (!isAudioFacility){
                    $F.alert(i18n.error.audioDeviceState);
                } else {
                    roomId = acceptRoomId ? acceptRoomId : roomId
                    // 初始化
                    avdEngine.init(serverURL, accessToken).then(initSuccess).inspect(initError)
                }
            }

            function initSuccess() {
                // 传入房间号获取房间对象。如房间存在,直接返回，不存在时创建房间后返回
                room = avdEngine.obtainRoom(roomId);
                room.join(userId, $E.staff.loginName, '', null).then(joinSuccess).inspect(joinError);
            }

            function initError(error) {
                $F.alert(i18n.error.AVDEngineInitFailed);
            }

            function createRequest() {
                const sentInfoJSON = JSON.stringify({
                    sessionId: sessionId,
                    roomId: roomId,
                    actionType: "createRequest",
                    from: 2
                });
                callService({
                    data: {
                        requestType: "videoMeetingEvent",
                        data: sentInfoJSON
                    },
                    success: data => {
                        console.log('videoMeetingEvent-data', data)
                    }
                }, true).fail(function (error) {
                    $F.alert(i18n.error.uploadFailed + 'createVideoRequest: ' + error);
                });
            }


            function joinSuccess() {
                acceptRoomId ? '' : createRequest()
                $('.meeting .users', Container).html(userName);
                $('.meeting.videoMeet', Container).show();
                $('.meeting.videoMeet .video', Container).show();
                $('.meeting.videoMeet .audio', Container).hide();

                $('#selfvideo', Container).show();
                $('.meeting.videoMeet .waitVideo', Container).show();

                // 调用 room.setUserAgent(USER_AGENT_AVD_MEDIA_MIXER_ADMIN) 用于设置房间（room）的用户代理为 USER_AGENT_AVD_MEDIA_MIXER_ADMIN。
                // 具体来说，这个用户代理可能用于标识客户端应用程序是 AVD Media Mixer Admin 的身份，以便服务器根据这个用户代理执行相应的逻辑。
                room.setUserAgent(USER_AGENT_AVD_MEDIA_MIXER_ADMIN);
                //  自动打开音视频
                Meet.closeCamera()
                Meet.closeMicrophone()
                Meet.openCamera();
                Meet.openMicrophone();
                registerRoomCallback();
                //加会登陆前，会议中已经发布的视频资源,采取订阅处理
                onPublishCameraNotify(room.pubVideos);
                // 处理房间内的参会者，给每个参会者添加回调事件
                participantsHandle(room.getParticipants());
            }

            function joinError(error) {
                if (error.code == 404) {
                    $F.alert(i18n.error.joinVideoMeetingFailed + error);
                } else {
                    $F.alert('joinError'+ error.message + "[" + error.code + "]");
                }
            }

            function registerRoomCallback() {
                room.addCallback(RoomCallback.connection_status, onConnectionStatus);
                room.addCallback(RoomCallback.user_join_notify, onUserJoinNotify);
                room.addCallback(RoomCallback.user_leave_notify, onUserLeaveNotify);
                room.addCallback(RoomCallback.user_leave_notify, onUserLeaveNotify);
                room.addCallback(RoomCallback.mcu_peerconnection_completed, onMCUPeerConnectionCompleted);
                room.addCallback(RoomCallback.connection_indicator, onConnectionIndicator);
            }

            function onMCUPeerConnectionCompleted() {
                console.log('+++'+ i18n.error.networkSituation+'...');
                room.connectionInfoCollector.start(); //开始收集网络情况,不填写频率参数，默认1000毫秒
                //room.connectionInfoCollector.stop();  //停止收集网络情况
            }

            /**
             * //房间级别
             roomConnection.localAddress   本地地址
             roomConnection.localPort      本地端口
             roomConnection.localProtocol  本地协议
             roomConnection.remoteAddress  远端地址
             roomConnection.remotePort     远端端口
             roomConnection.remoteProtocol  远端协议
             roomConnection.downloadBitrate  下载流量
             roomConnection.uploadBitrate    上传流量
             roomConnection.downloadPacket  下载数据包
             roomConnection.uploadPacket    上传数据包
             roomConnection.downloadPacketLost  下载数据包丢包数
             roomConnection.uploadPacketLost   上传数据包丢包数
             roomConnection.downloadPacketLossRate  下载数据包丢包率
             roomConnection.uploadPacketLossRate   上传数据包丢包率

             //某路音频相关
             var audioConnection = connectionIndicator.getAudioConnection(userId);
             audioConnection.downloadBitrate   音频下载流量
             audioConnection.uploadBitrate     音频上传流量
             audioConnection.downloadPacket   音频下载数据包
             audioConnection.uploadPacket     音频上传数据包
             audioConnection.packetsLost     音频数据包丢包数
             audioConnection.ssrc
             audioConnection.trackId
             audioConnection.payloadType
             audioConnection.mimeType
             audioConnection.clockRate

             //某路视频相关
             videoConnection = connectionIndicator.getVideoConnection(userId, cameraId);
             videoConnection.downloadBitrate   视频下载流量
             videoConnection.uploadBitrate     视频上传流量
             videoConnection.downloadPacket    视频下载数据包
             videoConnection.uploadPacket     视频传数据包
             videoConnection.packetsLost     视频数据包丢包数
             videoConnection.resolution        分辨率
             videoConnection.frameRate         帧率
             videoConnection.ssrc
             videoConnection.trackId
             videoConnection.payloadType
             videoConnection.mimeType
             videoConnection.clockRate

             //某路桌面共享相关
             screenConnection = connectionIndicator.getScreenConnection(userId);
             screenConnection.downloadBitrate   桌面共享下载流量
             screenConnection.uploadBitrate     桌面共享上传流量
             screenConnection.downloadPacket    桌面共享下载数据包
             screenConnection.uploadPacket     桌面共享传数据包
             screenConnection.packetsLost      桌面共享数据包丢包数
             screenConnection.resolution        分辨率
             screenConnection.frameRate         帧率
             screenConnection.ssrc
             screenConnection.trackId
             screenConnection.payloadType
             screenConnection.mimeType
             screenConnection.clockRate
             * @param {object} connectionIndicator 连接指示器
             */
            function onConnectionIndicator(connectionIndicator) {
                if (connectionIndicator) {
                    // var roomConnection = connectionIndicator.getRoomConnection();
                }
            }

            /**
             * @desc 网络状态回调
             * @param status - 状态码
             */
            function onConnectionStatus(status) {
                if (status == ConnectionStatus.connecting) {
                    $F.alert(i18n.error.networkFailure);
                } else if (status == ConnectionStatus.connected) {
                    //连接成功
                } else if (status == ConnectionStatus.reJoinConnected) {
                    //重新加会成功
                } else if (status == ConnectionStatus.reconnected) {
                    //重连接成功
                } else if (status == ConnectionStatus.connectFailed) {
                    $F.alert(i18n.error.networkrefailureReJoinMeet);
                    //应用层清场
                    if (room.connectionInfoCollector) {
                        room.connectionInfoCollector.stop(); //停止收集网络情况
                    }
                } else if (status == ConnectionStatus.reJoinRoomTimeOut) {
                    $F.alert(i18n.error.networkFailureReJoinMeet);
                    /**
                     * @desc 多次后重新加会超时后，开启持续永久重新加会
                     */
                    room.continuousReJoin();
                }
            }

            /**
             * @desc 参会者加会回调
             * @param {Object} users － 参会者数组
             */
            function onUserJoinNotify(users) {
                $('.meeting.videoMeet .waitAccept', Container).hide();
                $('.meeting.videoMeet .waitVideo', Container).show();
                $('#othervideo', Container).show()
                participantsHandle(users);
                Meet.mixRecordStartRequest()
            }

            /**
             * @desc 参会者退会回调
             * @param {int} opt - 退会类型
             * @param {int} reason  - 退会原因
             * @param {Object} user - 退会用户
             */
            function onUserLeaveNotify(opt, reason, user) {
                //UDP媒体通道建立超时807错误
                if (reason == 807) {
                    if (user.id == room.selfUser.id) {
                        console.log(i18n.error.udpConnectFaile)
                    } else {
                        console.log(user.name + i18n.error.udpConnectFaile)
                    }
                    return;
                }
                room.selfUser.attachVideoElementMediaStream(remoteVideo, null);
                remoteVideoIconAreaElement.classList.remove('removeVideoSvgActive');
                remoteAudioIconAreaElement.classList.remove('removeAudioSvgActive');
            }

            /**
             * @desc  用户回调事件
             * @param {Object} participants - 用户集数组
             */
            function participantsHandle(participants) {
                participants.forEach(function (user) {
                    user.addCallback(UserCallback.camera_status_notify, onCameraStatusNotify);
                    user.addCallback(UserCallback.microphone_status_notify, onMicrophoneStatusNotify);
                    user.addCallback(UserCallback.publish_camera_notify, onPublishCameraNotify);
                    user.addCallback(UserCallback.unpublish_camera_notify, onUnpublishCameraNotify);
                    user.addCallback(UserCallback.subscrible_camera_result, onSubscribleCameraResult);
                    user.addCallback(UserCallback.unsubscrible_camera_result, onUnsubscribleCameraResult);
                    user.addCallback(UserCallback.subscrible_microphone_result, onSubscribleMicrophoneResult);
                    user.addCallback(UserCallback.unsubscrible_microphone_result, onUnsubscribleMicrophoneResult);
                })
            }

            /**
             * 麦克风状态更新
             * @param {Object} status － 状态
             * @param {Object} microphoneId － 麦克风设备Id
             * @param {Object} microphoneName － 麦克风设备名称
             * @param {Object} userId － 麦克风设备所属者ＩＤ
             */
            function onMicrophoneStatusNotify(status, microphoneId, microphoneName, userId) {
                if (userId == room.selfUser.id) {
                    if (status == StreamStatus.published) {
                    } else if (status == StreamStatus.init) {
                    }
                } else {
                    if (status == StreamStatus.published) {
                        remoteAudioIconAreaElement.classList.add('removeAudioSvgActive');
                    } else if (status == StreamStatus.init) {
                        remoteAudioIconAreaElement.classList.remove('removeAudioSvgActive');
                    }
                }
            }

            /**
             * 房间中发布的视频回调
             * @param {Object} video-发布视频集
             */
            function onUnpublishCameraNotify(video) {
                video.unsubscrible();
            }

            /**
             * 摄像头状态更新
             * @param {Object} status － 状态
             * @param {Object} cameraId － 摄像头设备Id
             * @param {Object} cameraName－ 摄像头设备名称
             * @param {Object} userId－ 摄像头设备所属者ＩＤ
             */
            function onCameraStatusNotify(status, cameraId, cameraName, userId) {
                if (userId == room.selfUser.id) {
                    if (status == StreamStatus.published) {

                    } else if (status == StreamStatus.init) {

                    }
                } else {
                    if (status == StreamStatus.published) {
                        remoteVideoIconAreaElement.classList.add('removeVideoSvgActive');
                    } else if (status == StreamStatus.init) {
                        remoteVideoIconAreaElement.classList.remove('removeVideoSvgActive');
                    }
                }
            }

            //订阅未订阅的视频
            function onPublishCameraNotify(videos) {
                videos.forEach(function (video) {
                    //只订阅未订阅过的视频
                    var subVideoIdsLen = room.selfUser.subVideoIds.length;
                    if (subVideoIdsLen > 0) {
                        var isSub = false;
                        for (var i = 0; i < subVideoIdsLen; i++) {
                            var videoId = room.selfUser.subVideoIds[i];
                            if (video.id == videoId) {
                                isSub = true;
                                break;
                            }
                        }
                        if (!isSub) {
                            video.subscrible();
                        }
                    } else {
                        video.subscrible();
                    }
                });
            }

            /**
             * 订阅远端视频流反馈
             * @param {Object} stream － 远端视频流
             * @param {Object} userId － 所属用户ＩＤ
             * @param {Object} userName－ 所属用户名称
             * @param {Object} cameraId－ 摄像头设备ＩＤ
             */
            function onSubscribleCameraResult(stream, userId, userName, cameraId) {
                remoteVideoIconAreaElement.classList.add('removeVideoSvgActive');
                room.selfUser.attachVideoElementMediaStream(remoteVideo, stream);
            }

            /**
             * 取消订阅远端视频流反馈
             * @param {Object} userId－ 所属用户ＩＤ
             * @param {Object} userName－所属用户名称
             * @param {Object} cameraId－摄像头设备ＩＤ
             */
            function onUnsubscribleCameraResult(userId, userName, cameraId) {
                room.selfUser.attachVideoElementMediaStream(remoteVideo, null);
            }

            /**
             * 订阅远端音频流反馈
             * @param {Object} stream－ 远端音频流
             * @param {Object} userId－ 所属用户ＩＤ
             * @param {Object} userName－所属用户名称
             */
            function onSubscribleMicrophoneResult(stream, userId, userName) {
                remoteAudioIconAreaElement.classList.add('removeAudioSvgActive');
                room.selfUser.attachAudioElementMediaStream(remoteAudio, stream);
            }

            /**
             * 取消订阅远端音频流反馈
             * @param {Object} userId－ 所属用户ＩＤ
             * @param {Object} userName－所属用户名称
             */
            function onUnsubscribleMicrophoneResult(userId, userName) {
                room.selfUser.attachAudioElementMediaStream(remoteAudio, null);
            }
            $('.meeting .caller .video .setCon .right .videoBox .audioIconArea', Container).off('click')
            $('.meeting .caller .video .setCon .right .videoBox .audioIconArea', Container).click(function () {
                if (isOpenAudioShow) {
                    Meet.closeMicrophone()
                } else {
                    Meet.openMicrophone()
                }
            })
            $('.meeting .caller .video .setCon .right .videoBox .videoIconArea', Container).off('click')
            $('.meeting .caller .video .setCon .right .videoBox .videoIconArea', Container).click(function () {
                if (isOpenVideoShow) {
                    Meet.closeCamera()
                } else {
                    Meet.openCamera()
                }
            })
        },
        mixRecordStartRequest: function () {
            restApi
                .mixRecordStart(accessToken, roomId)
                .then((res) => {
                    console.log('mixRecordStartRequestSuccess', res)
                })
                .catch((error) => {
                    $F.alert(i18n.error.requestFailed + ',mixRecordStartRequest:' + error);
                })
        },
        mixRecordEndRequest: function () {
            restApi
                .mixRecordEnd(accessToken, roomId)
                .then((res) => {
                    if(res.data && res.data.length>0){
                    Meet.addVideoURlRequest(res.data[0].play_url,res.data[0].download_url)
                    }
                    console.log('mixRecordEndRequestSuccess', res)
                })
                .catch((error) => {
                    console.log(i18n.error.requestFailed + ',mixRecordEndRequest:' + error);
                })
        },
        addVideoURlRequest: function (playUrl,DownloadUrl) {
            const sentInfoJSON = JSON.stringify({
                sessionId: sessionId.toString(),
                roomId: roomId.toString(),
                from: 2,
                videoPlayUrl:playUrl,
                videoDownloadUrl:DownloadUrl
            });
            callService({
                data: {
                    requestType: "addVideoMeetingUrl",
                    data: sentInfoJSON
                },
                success: data => {
                    // Meet.clearSessionRequest(sessionId,roomId)
                }
            }, true).fail(function (error) {
                console.log(i18n.error.requestFailed + ',addVideoURlRequest:' + error);
            });
        },
        unAnsweredVedioRequest: function (unAnsweredSessionId, unAnsweredRoomId) {
            const sentInfoJSON = JSON.stringify({
                sessionId: unAnsweredSessionId.toString(),
                roomId: unAnsweredRoomId.toString(),
                actionType: "noResponse",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {

                }
            }, true).fail(function (e) {

            });
        },

        levelRoomRequest: function () {
            const sentInfoJSON = JSON.stringify({
                sessionId: sessionId.toString(),
                roomId: roomId.toString(),
                actionType: "leaveRoom",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {
                    $F.log("会议结束")
                }
            }, true).fail(function (e) {

            });
        },
        clearSessionRequest: function (clearSessionId, clearRoomId) {
            const sentInfoJSON = JSON.stringify({
                sessionId: clearSessionId.toString(),
                roomId: clearRoomId.toString(),
                actionType: "clearSession",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {
                }
            }, true).fail(function (e) {
                $F.alert(i18n.error.requestFailed + ',clearSessionRequest:' + error);
            });
        },
        cancelRequest: function () {
            const sentInfoJSON = JSON.stringify({
                sessionId: sessionId.toString(),
                roomId: roomId.toString(),
                actionType: "cancelRequest",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {
                    sendMessage(`${i18n.videoMeetingRecord.Cancel} [videoMeet]`, sessionId)
                }
            }, true).fail(function (error) {
                $F.alert(i18n.error.requestFailed + ',cancelRequest:' + error);
            });
        },
        openCamera: function () {
            if (!room) {
                return
            }
            if (!isOpenVideoShow) {
                isOpenVideoShow = true;
                videos = room.selfUser.videos;
                if (videos && videos.length > 0) {
                    var video = videos[0];
                    if (video) {
                        localVideoId = video.id;
                        video.previewAndPublish(localVideo)
                        videoIconAreaElement.classList.add('videoSvgActive');
                    }
                }
            }
        },
        openMicrophone: function () {
            if (!room) {
                return
            }
            if (!isOpenAudioShow) {
                isOpenAudioShow = true;
                // 获取audio对象
                var audio = room.selfUser.audio;
                localAudioId = audio.id;
                if (audio) {
                    audio.openMicrophone()
                    audioIconAreaElement.classList.add('audioSvgActive');
                }
            }
        },
        closeCamera: function () {
            if (!room) {
                return
            }
            if (isOpenVideoShow) {
                isOpenVideoShow = false
                var meetVideo = room.selfUser.getVideo(localVideoId);
                if (meetVideo) {
                    meetVideo.unpreview();
                    meetVideo.unpublish();
                    videoIconAreaElement.classList.remove('videoSvgActive');
                }
            }
        },
        closeMicrophone: function () {
            if (!room) {
                return
            }
            if (isOpenAudioShow) {
                isOpenAudioShow = false;
                var meetAudio = room.selfUser.getAudio(localAudioId);
                if (meetAudio) {
                    meetAudio.closeMicrophone();
                    audioIconAreaElement.classList.remove('audioSvgActive');
                }
            }
        },
        leaveRoom: function () {
            console.log('leaveRoom--room', room)
            if (!room) {
                // return
            }else{
            var reason = 1; //退会原因
            room.leave(reason).then(function () {
                Meet.mixRecordEndRequest()
                return false;
            })
            }
        },
    }

    return {
        loadSanTiMeet: Meet.init,
        leaveRoom: Meet.leaveRoom,
        closeCamera: Meet.closeCamera,
        closeMicrophone: Meet.closeMicrophone,
        openMicrophone: Meet.openMicrophone,
        openCamera: Meet.openCamera,
        levelRoomRequest: Meet.levelRoomRequest,
        clearSessionRequest: Meet.clearSessionRequest,
        cancelRequest: Meet.cancelRequest,
        mixRecordEndRequest:Meet.mixRecordEndRequest,
        mixRecordStartRequest:Meet.mixRecordStartRequest,
        addVideoURlRequest:Meet.addVideoURlRequest,
        unAnsweredVedioRequest:Meet.unAnsweredVedioRequest
    };

})
